<template>
    <view class="body-view1">
        <!--导航和状态栏-->
        <view class="state-navigation">
            <view class="slim_header_navigation d-flex a-center j-center">
                <view class="left_box" @tap="goBack">
                    <image src="/static/center/back.png" class="back"></image>
                </view>
                <view class="title">方案广场</view>

                <view class="right_box">
                    <text v-if="type==='pick'" @tap="submit" style="font-size:30rpx;font-weight:400;color:#1DC691;">确认</text>
                    <!-- <view @tap="openSt" class="st_btn" v-if="type!=='pick'&&VER.ver">声明与文献</view> -->
                </view>

            </view>
        </view>
        <view  class="content" style="top: calc(100rpx + var(--status-bar-height))">
            <!-- 顶部位置占位 -->
            <!-- <view
                style="height: calc(120rpx + var(--status-bar-height))"
            ></view> -->
            <pullScroolView
                class="scr"
                v-if="pageData.list?.length > 0"
                ref="scroll"
                :back-top="false"
                :pullDown="refresh"
                :pullUp="scrolltolower"
            >
                <view class="scrool-view d-flex wrap j-between">
                    <view
                        v-for="item in pageData.list"
                        @tap="goProgrammDetails(item.id)"
                        class="scrool-cell selected"
                    >
                        <!-- <view
                            v-if="type !== 'pick' && item.inUse == 1"
                            class="in-use"
                            >使用中</view
                        > -->
                        <view class="page-view d-flex a-center j-center">
                            <view class="page-view-number">{{
                                item.pageView
                            }}</view>
                            <i
                                class="icon icon-zhanshifanwei"
                                style="
                                    font-size: 25rpx;
                                    color: #ffffff;
                                    line-height: 33;
                                "
                            ></i>
                        </view>
                        <image class="cell-img" :src="item.photo"></image>
                        <view class="cell-info d-flex a-center j-between">
                            <view class="info-name" style="width:340rpx;">{{ item.name }}</view>
                            <!-- <view class="info-collect d-flex a-center">
                                <i
                                    class="icon icon-aixin"
                                    style="font-size: 30rpx; color: #1dc691"
                                ></i>
                                <view class="info-collect-number">{{
                                    item.favoritesCount
                                }}</view>
                            </view> -->
                        </view>
                        <view class="cell-introduction">{{
                            formatIntroduction(item.introduction)
                        }}</view>
                        <view
                            v-if="type === 'pick'"
                            class="check_box"
                            @tap.stop="toggleCheck(item)"
                        >
                            <image
                                v-if="inGroup(item)"
                                class="checkImg"
                                style="width: 32rpx; height: 32rpx"
                                src="@/static/image/diet-menu-check-true.png"
                            ></image>
                            <image
                                v-else
                                class="checkImg"
                                style="width: 32rpx; height: 32rpx"
                                src="@/static/image/sports-menu-check-false.png"
                            ></image>
                        </view>
                        <view
                            v-if="type === 'pick' && inGroup(item)"
                            class="shadow"
                        ></view>
                    </view>
                </view>
            </pullScroolView>
            <!-- <view class="bottom-btn d-flex j-center">
                <tm-button
                    _style="margin: 0;font-weight: 600;"
                    :width="690"
                    :height="80"
                    :shadow="-1"
                    round="5"
                    :linear-color="['#64F1C5', '#29DBA3']"
                    linear="left"
                    :fontSize="32"
                    fontColor="#ffffff"
                    label="创建方案"
                    @tap="goProgrammeCreate"
                ></tm-button>
            </view> -->
        </view>
        <view v-if="pageData.list?.length === 0" class="page-null d-flex d-c a-center j-center">
            <image
                mode="widthFix"
                style="width: 360rpx"
                src="/static/img/nodata.png"
            />
            <view class="page-null-text"
                >还没有方案</view
            >
            <!-- <tm-button
                _style="margin: 160rpx 0 0 0;font-weight: 600;"
                :width="390"
                :height="80"
                :shadow="-1"
                round="5"
                :linear-color="['#64F1C5', '#29DBA3']"
                linear="left"
                :fontSize="32"
                fontColor="#ffffff"
                label="创建方案"
                @tap="goProgrammeCreate"
            ></tm-button> -->
            <!-- <tm-button
                _style="margin: 40rpx 0 0 0;font-weight: 600;"
                :width="390"
                :height="80"
                :shadow="-1"
                round="5"
                :fontSize="32"
                color="#29DBA3"
                :outlined="true"
                fontColor="#29DBA3"
                label="去方案广场"
            ></tm-button> -->
        </view>
    </view>
    <statement ref="stPopup"></statement>
</template>

<script setup lang="tsx" name="programme">
import { userData as userDataStore } from "@/store/userData";
import { ref, computed } from "vue";
import { onLoad, onShow,onPageScroll } from "@dcloudio/uni-app";
import { getUserPlanList, getGroupPlan, editGroupPlan,getPublicPlanList } from "@/api/api";
import statement from "@/components/statement.vue";
import { ver } from "@/store/ver";
const VER = ver();
const stPopup = ref(null);
const openSt = ()=>{
    stPopup.value.open();
}

onPageScroll((res) => {
    const scrollTop = res.scrollTop;
    if(res.scrollTop===0){
        backTop();
        setTimeout(()=>{
            uni.pageScrollTo({scrollTop:100});
        },100)
    }
});

const backTop = ()=>{
    scroll.value.onBackTop();
}

const oldGroupPlan = ref([]);
const newGroupPlan = ref([]);

const type = ref("");
const groupId = ref("");


const inGroup = computed(() => (item: any) => {
    return newGroupPlan.value.some((gPlan) => gPlan.id === item.id);
});

const toggleCheck = (item) => {
    const index = newGroupPlan.value.findIndex((g) => g.id === item.id);
    if (index === -1) {
        newGroupPlan.value.push(item);
    } else {
        newGroupPlan.value.splice(index, 1);
    }
};

const adds = () => {
    let arr = [];
    newGroupPlan.value.forEach((newItem) => {
        if (oldGroupPlan.value.every((oldItem) => oldItem.id !== newItem.id)) {
            arr.push(newItem);
        }
    });

    return arr;
};
const subs = () => {
    let arr = [];
    oldGroupPlan.value.forEach((oldItem) => {
        if (newGroupPlan.value.every((newItem) => newItem.id !== oldItem.id)) {
            arr.push(oldItem);
        }
    });
    return arr;
};

let loading = false;

const submit = async () => {
    if(loading){
        return;
    }

    loading = true;

    let _adds = adds();
    let _subs = subs();
    const params = {
        groupId: groupId.value,
        addPlanId: _adds.map((item) => item.id),
        delPlanId: _subs.map((item) => item.id),
    };
    const res = await editGroupPlan(params).catch(()=>{
        loading = false;
    });

    const { flag } = res;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: "修改群方案失败",
            duration: 2000,
        });
        loading = false;
        return;
    }

    uni.showToast({
            icon: "success",
            title: "成功",
            duration: 2000,
        });

    setTimeout(()=>{
        goBack();
    },1500)


};

const goBack = () => {
    uni.navigateBack();
};
const userData: any = userDataStore();
let pageData: any = ref({});
let params: any = {
    planType:2,
    //userId:10000013,
    page: 1,
    rows: 6,
};
//页面加载完成后加载初始数据
onLoad((option) => {
    setTimeout(() =>{
        uni.pageScrollTo({scrollTop:100});
    },100)
    if (option.groupId) {
        type.value = option.type;
        groupId.value = option.groupId;
        GetGroupPlan(option.groupId);
    }
});
onShow(() => {
    refresh();
});

const GetGroupPlan = async (groupId: any) => {
    const params = {
        groupId,
    };
    const res = await getGroupPlan(params);
    console.log("GetGroupPlan");
    console.log("GetGroupPlan");
    console.log("GetGroupPlan");
    console.log(res);
    oldGroupPlan.value = JSON.parse(JSON.stringify(res.data.list));
    newGroupPlan.value = res.data.list;
};

const scroll = ref();
//下拉刷新数据
const refresh = () => {
    params.page = 1; //设置刷新时查询第一页
    getPublicPlanList(params).then((res: any) => {
        if (res.success) {
            params.page++; //设置下一页
            pageData.value = res.data;
            
            setTimeout(() => {
                scroll.value.success();
            }, 500);
        }
    });
};
//下拉加载
const scrolltolower = () => {
    if (params.page >= pageData.value.pages) return;
    getPublicPlanList(params).then((res: any) => {
        params.page++; //设置下一页
        pageData.value.list.push(...res.data.list);
    });
};
const goProgrammeCreate = () => {
    uni.navigateTo({
        url: `/pages/programmeCreate/programmeCreate`,
    });
};
const goProgrammDetails = (id: string) => {
    uni.navigateTo({
        url: `/pages/programmeDetails/programmeDetails?programmeId=${id}&&from=group`,
    });
};
const formatIntroduction = (str: string) => {
    return str.replace(/\n/g, "").replace(/\s/g, "");
};
</script>

<style lang="scss" scoped>
@import "./programme.scss";
.body-view1{
    width: 750rpx;
    height: calc(100vh + 1px);
}
.content{
    position:fixed;
    left:0;
    right:0;
    bottom:0;
    .scr{
        flex:1;
    }
}
</style>
